package com.mdinfo.system.service.impl;

import com.mdinfo.base.common.bean.CommonResult;
import com.mdinfo.base.common.bean.DataGrid;
import com.mdinfo.base.common.bean.MemberInfo;
import com.mdinfo.base.common.bean.Ref;
import com.mdinfo.base.utils.SystemUtil;
import com.mdinfo.base.utils.ListUtil;
import com.mdinfo.base.utils.Md5Util;
import com.mdinfo.base.utils.TimeUtil;
import com.mdinfo.system.bean.*;
import com.mdinfo.system.mapper.*;
import com.mdinfo.system.param.MemberParam;
import com.mdinfo.system.service.IDeptService;
import com.mdinfo.system.service.IMemberService;
import com.mdinfo.system.vo.MemberVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/11/30.
 */
@Service
@Transactional
public class MemberServiceImpl implements IMemberService {

    @Resource
    private SysMemberMapper memberMapper;
    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private SysEmpMapper empMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysMemberRoleMapper memberRoleMapper;
    @Resource
    private IDeptService deptService;
    @Resource
    private SysMenuMapper menuMapper;
    @Resource
    private SysMemberMapper2 memberMapper2;


    /**
     * 新增用户
     */
    public CommonResult<Void> add(MemberParam.AddParam param){

        SysDept dept = deptMapper.selectById(param.getDeptId());
        if(dept==null){
            return Ref.error("错误的部门编号");
        }
        SysEmp emp = empMapper.selectById(param.getEmpId());
        if(emp==null){
            return Ref.error("错误的人员编号");
        }
        SysMember member = memberMapper.getByUsername(param.getUsername());
        if(member!=null){
            return Ref.error("该用户名已经存在");
        }
        member = memberMapper.getByEmpId(param.getEmpId());
        if(member!=null){
            return Ref.error("该人员已经创建过用户");
        }

        member = new SysMember();
        member.setUsername(param.getUsername());
        member.setDeptId(param.getDeptId());
        member.setCreateTime(new Date());
        member.setUsable(1);
        member.setEmpId(param.getEmpId());

        String salt = Md5Util.getSalt();
        String dbPwd = Md5Util.makePwd(param.getPassword(),salt);
        member.setPassword(dbPwd);
        member.setSalt(salt);

        memberMapper.insert(member);
        return Ref.ok();
    }

    /**
     * 用户列表
     */
    public CommonResult<DataGrid<MemberVo.ListQueryVo>> listQuery(MemberParam.ListQueryParam param){

        MemberInfo info = SystemUtil.getInfo();
        List<SysMember> members = memberMapper2.listQuery(
                param.getStart(), param.getNum(),
                param.getDeptId(), param.getKey(), info.getDeptIdList());
        int count = memberMapper.countListQuery(param.getDeptId(),param.getKey(),info.getDeptIdList());

        List<MemberVo.ListQueryVo> vos = members.stream()
            .map(member->{
                MemberVo.ListQueryVo vo = new MemberVo.ListQueryVo();
                vo.setCreateTime(TimeUtil.formater(member.getCreateTime()));
                vo.setLastLoginTime(member.getLastLoginTime()==null?"":TimeUtil.formater(member.getLastLoginTime()));
                vo.setMemberId(member.getId());
                vo.setUsable(member.getUsable());
                vo.setUsername(member.getUsername());
                SysEmp emp = empMapper.selectById(member.getEmpId());
                if(emp!=null){
                    vo.setEmpName(emp.getName());
                }
                SysDept dept = deptMapper.selectById(member.getDeptId());
                if(dept!=null){
                    vo.setDeptName(dept.getShortName());
                }
                List<SysRole> roles = roleMapper.listByMemberId(member.getId());
                roles.forEach(role->{
                    MemberVo.MemberRoleVo roleVo = new MemberVo.MemberRoleVo();
                    roleVo.setRoleId(role.getId());
                    roleVo.setRoleName(role.getName());
                    vo.getRoles().add(roleVo);
                });
                return vo;
            }).collect(Collectors.toList());
        DataGrid<MemberVo.ListQueryVo> dataGrid = new DataGrid<>();
        dataGrid.setRows(vos);
        dataGrid.setTotal(count);

        return Ref.ok(dataGrid);
    }

    /**
     * 修改用户
     */
    public CommonResult<Void> modify(MemberParam.ModifyParam param){
        SysMember member = memberMapper.selectById(param.getMemberId());
        if(member==null){
            return Ref.error("错误的用户编号");
        }
        member.setUsable(param.getUsable());
        memberMapper.updateById(member);

        List<SysRole> roles = roleMapper.listByMemberId(member.getId());
        List<Integer> dbRoleIdList = roles.stream().map(role-> {
            return role.getId();
        }).collect(Collectors.toList());

        //获取页面参数中有,数据库中没有的  需要插入
        List<Integer> needInsert = ListUtil.difference(param.getRoleIdList(), dbRoleIdList);
        //获取页面参数中没有,数据库中有的  需要删除
        List<Integer> needDelete = ListUtil.difference(dbRoleIdList,param.getRoleIdList());

        //删除
        if(needDelete.size()>0){
            memberRoleMapper.deleteByList(param.getMemberId(),needDelete);
        }

        //插入
        needInsert.forEach(roleId->{
            SysMemberRole mr = new SysMemberRole();
            mr.setMemberId(param.getMemberId());
            mr.setRoleId(roleId);
            memberRoleMapper.insert(mr);
        });

        return Ref.ok();
    }


    /**
     * 用户登录
     */
    public CommonResult<MemberVo.LoginVo> login(MemberParam.LoginParam param){

        SysMember member = memberMapper.getByUsername(param.getUsername());
        if(member==null){
            return Ref.error("错误的用户名或密码");
        }
        String salt = member.getSalt();
        String dbPwd = Md5Util.makePwd(param.getPassword(), salt);
        if(!dbPwd.equals(member.getPassword())){
            return Ref.error("错误的用户名或密码");
        }
        if(member.getUsable()==0){
            return Ref.error("该用户已被禁用");
        }

        member.setLastLoginTime(new Date());
        memberMapper.updateById(member);

        //获取用户所能访问的部门id
        List<Integer> deptIdList = deptService.myDeptIdList(member.getDeptId());

        //保存到redis中的数据
        MemberInfo info = new MemberInfo();
        //返回客户端的数据
        MemberVo.LoginVo vo = new MemberVo.LoginVo();

        //获取当前用户的权限
        List<SysMenu> sysMenus = menuMapper.listByMemberId(member.getId());
        sysMenus.forEach(menu->{
            MemberInfo.MenuVo menuVo = new MemberInfo.MenuVo();
            menuVo.setMenuId(menu.getId());
            menuVo.setMenuName(menu.getName());
            menuVo.setMenuTag(menu.getTag());
            info.getMenuList().add(menuVo);
        });

        SysEmp emp = empMapper.selectById(member.getEmpId());
        if(emp!=null){
            info.setEmpName(emp.getName());
            vo.setEmpName(emp.getName());
        }

        SysDept dept = deptMapper.selectById(member.getDeptId());
        if(dept!=null){
            info.setDeptShortName(dept.getShortName());
            info.setDeptFullName(dept.getFullName());
            vo.setDeptShortName(dept.getShortName());
            vo.setDeptFullName(dept.getFullName());
            vo.setDeptPid(dept.getPid());
            vo.setLng(dept.getLng());
            vo.setLat(dept.getLat());
            vo.setZoom(dept.getZoom());
        }else{
            vo.setDeptPid(0);
        }

        info.setDeptId(member.getDeptId());
        info.setEmpId(member.getEmpId());
        info.setMemberId(member.getId());
        info.setUsername(member.getUsername());
        info.setDeptIdList(deptIdList);
        info.setDeviceId(param.getDeviceId());
        info.setDeviceType(param.getDeviceType());

        //生成token
        String token = SystemUtil.createToken(info);
        vo.setToken(token);
        vo.setUsername(param.getUsername());
        vo.setDeptId(member.getDeptId());
        vo.setMyDeptIdList(deptIdList);
        vo.setMemberId(member.getId());

        return Ref.ok(vo);
    }

    /**修改密码*/
    public CommonResult<Void> changePass(MemberParam.ChangePassParam param){

        SysMember member = memberMapper.selectById(param.getMemberId());
        if(member==null){
            return Ref.error("错误的用户id");
        }
        String dbPass = Md5Util.makePwd(param.getOldPass(), member.getSalt());
        if(!dbPass.equals(member.getPassword())){
            return Ref.error("旧密码错误");
        }
        dbPass = Md5Util.makePwd(param.getNewPass(),member.getSalt());
        member.setPassword(dbPass);
        memberMapper.updateById(member);
        return Ref.ok();
    }
}
